import { ExclamationCircleFilled } from '@ant-design/icons';
import './textChat.scss'
import TextInput, { type TextInputRef } from '../../components/TextInput'
import { forwardRef, memo, useEffect, useRef, useState } from "react";
import { useAppSelector } from "../../utils/storeHook/storeHook";
import http from "../../utils/http";
import api from "../../api";
import { message, Skeleton } from "antd";
import { MessageItem, PageDisabled } from "../../components";
import socketService from "../../services/socketService"; // 导入服务
import { useNavigate } from 'react-router-dom';

interface MessageItemT{
    message_id:string,
    channel_id:string,
    content:string,
    sender_id:string,
    created_at:string,
    sender_avatar:string,
    sender_name:string
}
interface ChannelInfo{
    channelName:string,
    channel_id:string,
    can_connect:boolean,
    can_manage:boolean,
    can_send:boolean,
    can_view:boolean,
    is_muted:boolean,
}

interface AttachmentT {
    file_id: string;
    file_url: string;
    file_name?: string;
    width?: number;
    height?: number;
    size: number;
    mime_type: string;
    alt_text?: string;
}

interface MensionT {
    id: string;
    name: string;
}

interface messageInpT {
    text: string;
    attachments?: AttachmentT[];
    mention?:MensionT,
    recorder?:AttachmentT
}

interface propsT{
    actChannelId:string
    inputActions?:string[]
}

const TextChat=memo(forwardRef(({actChannelId,inputActions=['emotion','picture','file','recorder']}:propsT)=>{
    const [messageApi, contextHolder] = message.useMessage();
    const navigate = useNavigate()

    const textInpRef = useRef<TextInputRef>(null)
    const messageListRef = useRef<HTMLDivElement>(null)

    const actServerId = useAppSelector(state=>state.channel.actServerId)
    const isConnect = useAppSelector(state=>state.server.isConnect)
    const userType = useAppSelector(state=>state.auth.userType)
    
    const [isLoading,setIsloading] = useState(true)
    // const [mension,setMension] = useState<MensionT>()
    const [messageList,setMessageList] = useState<MessageItemT[]>([])
    const [moreMessageList,setMoreMessageList] = useState<MessageItemT[]>([])
    const [userChannelInfo,setUserChannelInfo] = useState<ChannelInfo|null>()
    const [messageFiles, setMessageFiles] = useState<{[messageId:string]:string[]}>({})
    
    const [pagigation,setPagigation] = useState({
        pageCur:1,
        pageSize:20,
        total:0
    })

    async function getChannelMessageList(){
        await http.post(api.message.getChannelMessageList,{channel_id:actChannelId,server_id:actServerId,userType:userType,...pagigation}).then(res=>{
            const resData = res.data
            setPagigation({...pagigation,total:resData.totalMessage})
            setMessageList(resData.messageList)
            setUserChannelInfo({...resData.permission,channelName:resData.channelName,channel_id:resData.channel_id,user_id:resData.user_id})
            setIsloading(false)

            resData.messageList.forEach((item:MessageItemT)=>{
                const fileList:string[] = []
                const content = JSON.parse(item.content)
                if(content.attachments.length > 0){
                    content.attachments.forEach((item:AttachmentT)=>{
                        fileList.push(item.file_id)
                    })
                }
                if(content.recorder){
                    fileList.push(content.recorder.file_id)
                }
                if(fileList.length > 0){
                    setMessageFiles(prev=>({...prev,[item.message_id]:fileList}))
                }
            })

        }).catch(err=>{
            messageApi.error(err.message)
            setIsloading(false)
        })
        
    }

    function getMoreMessages(){
        setPagigation({...pagigation,pageCur:pagigation.pageCur+1})
        const submit = {
            channel_id:actChannelId,
            server_id:actServerId,
            userType:userType,
            pageCur:pagigation.pageCur+1,
            pageSize:pagigation.pageSize
        }
        http.post(api.message.getChannelMessageList,{...submit}).then(res=>{
            const resData = res.data
            setMoreMessageList(prev=>([...prev,...resData.messageList]))
        }).catch(err=>{
            messageApi.open({
                type:'error',
                content:err.message
            })
            setIsloading(false)
        })
    }

    function handleChange(messageInpItem:messageInpT){
        const content = JSON.stringify(messageInpItem)
        socketService.sendMessage(actChannelId,content).then(()=>{
            textInpRef.current?.clearInput()
            localStorage.setItem(actChannelId+'msg',JSON.stringify(''))
        })
        
        // const submit = {
        //     channel_id:actChannelId,
        //     content:content
        // }
        // http.post(api.message.sendChannelMessage,{...submit}).then(res=>{
        //     const resData = res.data
        //     textInpRef.current?.clearInput()
        //     localStorage.setItem(actChannelId+'msg',JSON.stringify(''))
        //     messageApi.success('发送成功')
        // }).catch(err=>{
        // })
    }

    function onDeleteMsg(id:string){

        socketService.deleteMessage(id)
        // http.post(api.message.deleteMessage,{message_id:id}).then(res=>{
        //     setMessageList(messageList.filter(item=>item.message_id!==id))
        //     messageApi.success('删除成功')
        // }).catch(err=>{
        //     messageApi.error(err.message)
        // })
    }

    // 处理收到的新消息
    function handleNewMessage(message: MessageItemT){
        // 转换为前端使用的消息结构
        setMessageList(prev=>[...prev, message]);
        const fileList:string[] = []
        const content = JSON.parse(message.content)
        if(content.attachments.length > 0){
            content.attachments.forEach((item:AttachmentT)=>{
                fileList.push(item.file_id)
            })
        }
        if(content.recorder){
            fileList.push(content.recorder.file_id)
        }
        if(fileList.length > 0){
            setMessageFiles(prev=>({...prev,[message.message_id]:fileList}))
        }
    };

    // 处理删除的消息
    function handleDelMessage({message_id}:{message_id:string,channel_id:string}){
        setMessageList(prev=>prev.filter(item=>item.message_id!==message_id))
    };

    useEffect(() => {
        // 清理函数：离开频道
        return () => {
            localStorage.removeItem(actChannelId+'msg')
            if (actChannelId) {
                socketService.leaveChannel(actChannelId);
            }
        };
    }, []);

    // 监听频道变化/拉取频道消息
    useEffect(()=>{
        if (!actChannelId || !isConnect) return;

        // 加入新频道
        socketService.joinChannel(actChannelId);
        
        // 设置消息监听器（新消息）
        socketService.onNewMessage(handleNewMessage);

        // 设置消息监听器（删除消息）
        socketService.onDelMessage(handleDelMessage);

        getChannelMessageList()
        return ()=>{
            socketService.offNewMessage();
            socketService.offDelMessage();
        }
    },[actChannelId,isConnect])

    useEffect(()=>{
        const scrollToNewestMsg = () => {
            if (messageListRef.current) {
                messageListRef.current.scrollTo({
                    top: messageListRef.current.scrollHeight,
                    behavior: 'smooth'
                });
            }
        };
        const timer = setTimeout(scrollToNewestMsg, 100);
        
        // 删除message时同步删除文件
        const messages = messageList.map(item=>item.message_id)
        Object.keys(messageFiles).forEach(key=>{ 
            if(!messages.includes(key)){
                messageFiles[key].forEach(file_id=>{
                    http.post(api.file.deleteFile,{file_id:file_id})
                })
                delete messageFiles[key]
            }
        })

        return () => clearTimeout(timer);
    },[messageList])

    return (
        <>
            {contextHolder}
            {userChannelInfo&&!userChannelInfo.can_view&&<PageDisabled></PageDisabled>}
            {isLoading&&
            <div className="skeleton"><Skeleton active paragraph={{rows:8}}></Skeleton></div>}
            <div className="textChat_box">
                <div className="textChat_header">
                    <div className="textChat_title">
                        <span>#</span>
                        <div>{userChannelInfo?.channelName}</div>
                    </div>
                </div>
                {userType=='guestUser'&&<div className="textChat_alert">
                    <span><ExclamationCircleFilled /></span>
                    <span>您当前是游客状态，</span>
                    <span className="textChat_click_text" onClick={() => navigate('/login')}>登录</span>
                    <span>以解锁全部功能（创建频道、语音聊天、添加好友等）</span>
                </div>}
                <div className="textChat_message">
                    <div className="textChat_messageList" ref={messageListRef}>
                        {pagigation.pageCur*pagigation.pageSize<pagigation.total&&<div className="textChat_showMore" onClick={getMoreMessages}>展开更多</div>}
                        {
                            messageList.length>0&&moreMessageList.map((item) =>
                            <div id={'MSG'+item.message_id} key={item.message_id}>
                                <MessageItem
                                    item={item} 
                                    onDelete={onDeleteMsg}
                                    id={item.message_id}
                                    isMGT={userChannelInfo?.can_manage ? true : false}
                                />
                            </div>)
                        }
                        {
                            messageList.length>0&&messageList.map((item) =>
                            <div id={'MSG'+item.message_id} key={item.message_id}>
                                <MessageItem
                                    item={item} 
                                    onDelete={onDeleteMsg}
                                    id={item.message_id}
                                    isMGT={userChannelInfo?.can_manage ? true : false}
                                />
                            </div>)
                        }
                    </div>
                    <div className="textChat_message_input">
                        <TextInput
                            onChange={handleChange}
                            // mensionVal={mension}
                            ref={textInpRef}
                            disabled={!userChannelInfo?.can_send}
                            channel_id={actChannelId}
                            actions={inputActions}
                        ></TextInput>
                    </div>
                </div>
            </div>
        </>
    )
}))

export default TextChat;